# -*- coding: utf-8 -*-
"""
历史记录管理器
管理计算历史记录的保存、读取和删除
"""

import json
import os
import sys
from datetime import datetime, date
from typing import Dict, List, Optional
import pendulum


class HistoryManager:
    """历史记录管理器"""
    
    def __init__(self):
        """初始化历史记录管理器"""
        # 获取项目根目录
        if getattr(sys, 'frozen', False):
            # 打包后的exe环境
            base_dir = os.path.dirname(sys.executable)
        else:
            # 开发环境
            base_dir = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
        
        self.history_file = os.path.join(base_dir, "data", "calculation_history.json")
        self.max_records = 1000  # 最大记录数
        self.ensure_data_dir()
        self.load_history()
    
    def _serialize_for_json(self, obj):
        """将对象序列化为JSON兼容格式"""
        if isinstance(obj, (datetime, date)):
            return obj.isoformat()
        elif hasattr(obj, 'format'):  # pendulum对象
            return obj.format('YYYY-MM-DD HH:mm:ss')
        elif hasattr(obj, 'isoformat'):
            return obj.isoformat()
        elif isinstance(obj, dict):
            return {k: self._serialize_for_json(v) for k, v in obj.items()}
        elif isinstance(obj, list):
            return [self._serialize_for_json(item) for item in obj]
        else:
            return str(obj) if obj is not None else None
    
    def ensure_data_dir(self):
        """确保数据目录存在"""
        data_dir = os.path.dirname(self.history_file)
        if not os.path.exists(data_dir):
            os.makedirs(data_dir)
    
    def load_history(self):
        """加载历史记录"""
        try:
            if os.path.exists(self.history_file):
                with open(self.history_file, 'r', encoding='utf-8') as f:
                    self.history = json.load(f)
            else:
                self.history = []
        except Exception as e:
            print(f"加载历史记录失败: {e}")
            self.history = []
    
    def save_history(self):
        """保存历史记录"""
        try:
            # 限制记录数量
            if len(self.history) > self.max_records:
                self.history = self.history[-self.max_records:]
            
            with open(self.history_file, 'w', encoding='utf-8') as f:
                json.dump(self.history, f, ensure_ascii=False, indent=2)
        except Exception as e:
            print(f"保存历史记录失败: {e}")
    
    def add_calculation_record(self, calc_type: str, input_data: Dict, result_data: Dict):
        """添加计算记录"""
        try:
            # 序列化所有数据
            serialized_input = self._serialize_for_json(input_data)
            serialized_result = self._serialize_for_json(result_data)
            
            record = {
                'id': len(self.history) + 1,
                'timestamp': datetime.now().isoformat(),
                'calc_type': calc_type,
                'input_data': serialized_input,
                'result_data': serialized_result,
                'formatted_time': datetime.now().strftime('%Y年%m月%d日 %H:%M:%S')
            }
            
            self.history.append(record)
            self.save_history()
            
        except Exception as e:
            print(f"添加历史记录失败: {e}")
    
    def get_history(self, limit: Optional[int] = None) -> List[Dict]:
        """获取历史记录"""
        if limit:
            return self.history[-limit:]
        return self.history
    
    def get_recent_history(self, days: int = 7) -> List[Dict]:
        """获取最近几天的历史记录"""
        try:
            cutoff_date = datetime.now().timestamp() - (days * 24 * 3600)
            recent_records = []
            
            for record in self.history:
                record_time = datetime.fromisoformat(record['timestamp']).timestamp()
                if record_time >= cutoff_date:
                    recent_records.append(record)
            
            return recent_records
            
        except Exception as e:
            print(f"获取最近历史记录失败: {e}")
            return []
    
    def delete_record(self, record_id: int):
        """删除指定记录"""
        try:
            self.history = [r for r in self.history if r['id'] != record_id]
            self.save_history()
        except Exception as e:
            print(f"删除记录失败: {e}")
    
    def clear_history(self):
        """清空所有历史记录"""
        try:
            self.history = []
            self.save_history()
        except Exception as e:
            print(f"清空历史记录失败: {e}")
    
    def export_history(self, file_path: str) -> bool:
        """导出历史记录"""
        try:
            with open(file_path, 'w', encoding='utf-8') as f:
                json.dump(self.history, f, ensure_ascii=False, indent=2)
            return True
        except Exception as e:
            print(f"导出历史记录失败: {e}")
            return False
    
    def import_history(self, file_path: str) -> bool:
        """导入历史记录"""
        try:
            with open(file_path, 'r', encoding='utf-8') as f:
                imported_history = json.load(f)
            
            # 合并历史记录
            self.history.extend(imported_history)
            self.save_history()
            return True
        except Exception as e:
            print(f"导入历史记录失败: {e}")
            return False
    
    def get_statistics(self) -> Dict:
        """获取使用统计"""
        try:
            stats = {
                'total_calculations': len(self.history),
                'date_calculations': 0,
                'time_calculations': 0,
                'lunar_conversions': 0,
                'most_used_function': '暂无',
                'first_use': '暂无',
                'last_use': '暂无'
            }
            
            if not self.history:
                return stats
            
            # 统计各类型计算数量
            type_counts = {}
            for record in self.history:
                calc_type = record.get('calc_type', 'unknown')
                type_counts[calc_type] = type_counts.get(calc_type, 0) + 1
                
                if 'date' in calc_type.lower() or '日期' in calc_type:
                    stats['date_calculations'] += 1
                elif 'time' in calc_type.lower() or '时间' in calc_type:
                    stats['time_calculations'] += 1
                elif 'lunar' in calc_type.lower() or '农历' in calc_type:
                    stats['lunar_conversions'] += 1
            
            # 最常用功能
            if type_counts:
                stats['most_used_function'] = max(type_counts, key=type_counts.get)
            
            # 首次和最后使用时间
            if self.history:
                stats['first_use'] = self.history[0].get('formatted_time', '未知')
                stats['last_use'] = self.history[-1].get('formatted_time', '未知')
            
            return stats
            
        except Exception as e:
            print(f"获取统计信息失败: {e}")
            # 返回默认统计信息而不是空字典
            return {
                'total_calculations': 0,
                'date_calculations': 0,
                'time_calculations': 0,
                'lunar_conversions': 0,
                'most_used_function': '暂无',
                'first_use': '暂无',
                'last_use': '暂无'
            }
